/**
 * @description service get-manifest
 *
 * @author xiaomi
 */

const axios = require('axios');
const Promise = require('bluebird');
const exec = require('child-process-promise').exec;
const cache = require('./cache');
const pkgs = require('../../package.json');

const IS_PROD = process.env.NODE_ENV === 'production';
// const PROJECT_NAME = '';

const MANIFESTS_MAP_CACHE_KEY_PREFIX = 'manifests_map_';
const MANIFESTS_MAP_CACHE_TTL = 3 * 24 * 60 * 60;

const getCommitHash = () => {
    return Promise.try(() => {
        return exec('git log -1 --format="%H"');
    })
    .then(({ stdout }) => {
        return String(stdout).slice(0, 7);
    });
};

const fetchManifestsMap = hash => {
    return Promise.try(() => {
        const baseUrl = process.env.CDN_URL;
        const path = '/manifest.json';
        // cache
        fetchManifestsMap.path = path;
        return axios.get(baseUrl + path);
    })
    .then(res => {
        return res.data || null;
    })
    .catch(err => {
        const msg = `Manifests map[${fetchManifestsMap.path}] load error: ${err.message}`;

        err.message = msg;

        throw err;
    });
};

const loadManifestsMap = () => {
    if(!IS_PROD) {
        return Promise.resolve({});
    }

    if(!loadManifestsMap.promise) {
        let commitHash, cacheKey;

        loadManifestsMap.promise = Promise.try(() => {
            return getCommitHash();
        })
        // .then(hash => {
        //     cacheKey = MANIFESTS_MAP_CACHE_KEY_PREFIX + hash;
        //     commitHash = hash;

        //     return cache.get(cacheKey, 'json');
        // })
        .then(map => {
            // if(map) {
            //     return map;
            // }

            return fetchManifestsMap();
            // // Cache
            // .tap(map => {
            //     return cache.set(cacheKey, map, MANIFESTS_MAP_CACHE_TTL);
            // });
        })
        .catch(err => {
            // Reset promise cache if error
            loadManifestsMap.promise = null;

            throw err;
        });
    }

    return loadManifestsMap.promise;
};

module.exports = (moduleName = 'www') => {
    return loadManifestsMap()
    .then(manifestsMap => {
        return manifestsMap[moduleName] || manifestsMap;
    });
};
